package com.hjn.springboot.springbootservlet.servlet;


import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class JavaUrlRequest {
    public static void main(String[] args) throws IOException {
        String urlpath = "http://127.0.0.1:8080/myservlet03";
        String param = "username=zhangsan&age=12";
        httpPost(urlpath,param);
    }

    /**
     * 使用java自带的http访问网站并发送post请求
     *
     * @param urlpath 网址
     * @param param   参数
     */
    private static void httpPost(String urlpath, String param) throws IOException {
        URL url = new URL(urlpath);
        URLConnection connection = url.openConnection();

        connection.setDoOutput(true);
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(param.getBytes("utf-8"));
        try (InputStream inputStream = connection.getInputStream();
             BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));) {
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String cookie = connection.getHeaderField("set-cookie");
        Map<String, List<String>> headerFields = connection.getHeaderFields();
        Set<Map.Entry<String, List<String>>> entries = headerFields.entrySet();
        entries.iterator().forEachRemaining((k)->{
            System.out.println(k.getKey() +"------------"+ k.getValue());
        });
        System.out.println(cookie);

    }

    private static void httpGet() {
        String urlPath = "http://www.baidu.com";
        URLConnection urlConnection = null;
        try {
            URL url = new URL(urlPath);
            //打开链接
            urlConnection = url.openConnection();
            urlConnection.setConnectTimeout(5000);
            urlConnection.setReadTimeout(5000);
            urlConnection.connect();
            InputStream inputStream = urlConnection.getInputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            int i = 0;
            byte[] b = new byte[1024];
            String string = null;
            while ((i = bufferedInputStream.read(b)) != -1) {
                string = new String(b, 0, i, "utf-8");
                System.out.println(string);
            }
            if (bufferedInputStream != null) {
                bufferedInputStream.close();
            }

        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
